package com.hysh.web.controller.face;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hysh.common.annotation.FaceLog;
import com.hysh.common.core.domain.AjaxResult;
import com.hysh.system.domain.Face;
import com.hysh.common.core.domain.FaceResult;
import com.hysh.system.server.FaceContrastServer;
import com.hysh.system.service.FaceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/face")
@Api("人脸验证接口")
@Slf4j
public class FaceController {

    @Autowired
    FaceService faceService;

    @Autowired
    FaceContrastServer faceContrastServer;

    // 比较邪乎了，为啥是30，不是20，其实20也可以，就是一个优化参数
    private static final int critical = 30;

    @PostMapping("/vef")
    @ApiOperation(value="人脸验证", notes="根据传入的base64编码和数据的base64编码进行对比")
    @FaceLog
    public FaceResult faceVef(@RequestBody String imageBase){
        return faceService.vef(imageBase);
    }

    @PostMapping("/compare")
    @ApiOperation("比对两个 base64 是否为同一个人")
    public FaceResult compareTwoFaces(@RequestBody Map<String, String> map) {
        String imageA = map.get("imageA");
        String imageB = map.get("imageB");
        return faceContrastServer.faceContrast(imageA, imageB);
    }

    @PostMapping("/liveDetect")
    @ApiOperation("腾讯云静态活体检测")
    public FaceResult liveDetect(@RequestBody Map<String, String> map) {
        String imageBase64 = map.get("imageBase64");
        if (imageBase64 == null || imageBase64.isEmpty()) {
            return FaceResult.error(FaceResult.NULL_ERROR, "图片不能为空");
        }
        return faceContrastServer.detectLiveFace(imageBase64);
    }

    @GetMapping("/faceList")
    @ApiOperation(value = "人脸列表",notes = "查询所有的人脸信息")
    public FaceResult faceList(
            @RequestParam Integer current,
            @RequestParam Integer size,
            @RequestParam(required = false) String faceName,
            @RequestParam(required = false) String faceStatus
    ){
        IPage<Face> page = faceService.page(new Page(current, size), new QueryWrapper<Face>()
                .like(StrUtil.isNotBlank(faceName),"face_name",faceName)
                .like(StrUtil.isNotBlank(faceStatus),"face_status",faceStatus));
        return FaceResult.success(page);
    }

    @GetMapping("/faceDelete/{fid}")
    @ApiOperation(value = "删除人脸",notes = "根据id进行删除")
    public FaceResult faceDelete(@PathVariable Integer fid){
        faceService.removeById(fid);
        return FaceResult.success("删除成功");
    }

    @GetMapping("/info/{fid}")
    @ApiOperation(value = "查询方法",notes = "根据id查询人脸信息")
    public FaceResult info(@PathVariable Integer fid){
        return FaceResult.success(faceService.getById(fid));
    }

    @PostMapping("/save")
    @ApiOperation(value = "添加")
    public FaceResult save(@RequestBody Face face){
        face.setVefNum(0);
        face.setCreateTime(new Date());
        faceService.save(face);
        return FaceResult.success("添加成功");
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public FaceResult update(@RequestBody Face face){
        faceService.updateById(face);
        return FaceResult.success("修改成功");
    }

    @PostMapping("/changeBackground")
    public AjaxResult changeBackground(@RequestParam("file") MultipartFile file,
                                       @RequestParam("color") String color) throws Exception {

        // 1. 保存临时文件
        File tempFile = File.createTempFile("upload", ".jpg");
        file.transferTo(tempFile);

        // 2. 根据 color 参数转成 RGB
        int targetRgb;
        switch (color.toLowerCase()) {
            case "red": targetRgb = new Color(255, 0, 0).getRGB(); break;
            case "blue": targetRgb = new Color(0, 0, 255).getRGB(); break;
            default: targetRgb = new Color(255, 255, 255).getRGB(); // 白色
        }

        // 3. 调用你的方法处理背景
        BufferedImage resultImage = handleBufferImageBackgroundRGB(tempFile.getAbsolutePath(), targetRgb, false);

        // 4. 保存到本地
        String saveDir = "E:/images/face";
        File dir = new File(saveDir);
        if (!dir.exists()) dir.mkdirs();

        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File outFile = new File(dir, fileName);
        ImageIO.write(resultImage, "jpg", outFile);

        // 5. 返回保存路径
        return AjaxResult.success(outFile.getAbsolutePath());
    }


    /***
     * 处理图片背景色
     * @param path 原图地址
     * @param targetRgb 目标颜色RGB值 16进制颜色码
     * @param isNetWork 原图是否为网络图片地址
     * @return
     */
    public static BufferedImage handleBufferImageBackgroundRGB(String path, int targetRgb, boolean isNetWork) throws Exception {
        File file;
        if (isNetWork) {
            // 处理网络图片，先将图片下载到临时文件
            file = File.createTempFile("download", ".jpg");
            HttpUtil.downloadFile(path, file);
        } else {
            file = new File(path);
        }

        // 用来处理图片的缓冲流
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            log.error("图像加载内存失败", e);
            throw e;
        }

        int width = bi.getWidth();
        int height = bi.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取左上角颜色，默认左上角像素块颜色为背景色
        int pixel = bi.getRGB(critical, critical);
        log.info("图片名称:{}, targetRgb:{}, width:{}, height:{}, pixel:{}",
                file.getName(), targetRgb, width, height, pixel);

        Graphics g = image.getGraphics();
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int nowPixel = bi.getRGB(x, y);
                int p = pixel == nowPixel ? targetRgb : nowPixel;
                g.setColor(new Color(p));
                g.fillRect(x, y, 1, 1);
            }
        }

        log.info("处理完毕：{}", file.getName());
        return image;
    }

}
